package cn.edu.seu.herald.informationplatform.dao.cookie;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;

import cn.edu.seu.herald.informationplatform.bean.auth.LeagueSession;
import cn.edu.seu.herald.informationplatform.bean.league.LeagueUser;
import cn.edu.seu.herald.informationplatform.dao.database.LeagueSessionDao;
import cn.edu.seu.herald.informationplatform.dao.database.LeagueUserDao;

public class LeagueUserSessionCookieAccess extends SessionCookieAccess {
	
	private LeagueSessionDao _leagueSessionDao;
	
	private LeagueUserDao _leagueUserDao;

	private static String SESSION_ID_COOKIE_NAME = "LEAGUE_USER_SESSION_ID";
	
	public LeagueUserSessionCookieAccess(HttpServletRequest request)
				throws SessionIdNotFound {
		super(request);
		_leagueSessionDao = LeagueSessionDao.getDao();
		_leagueUserDao = LeagueUserDao.getDao();
	}

	@Override
	public boolean isAuthorized() throws SQLException {
		int id = Integer.valueOf(getSessionId());
		return _leagueSessionDao.contains(id);
	}

	@Override
	public String getUsername() throws SQLException {
		int leagueId = getLeagueId();
		LeagueUser leagueUser = _leagueUserDao.getLeagueUser(leagueId);
		return leagueUser.getUsername();
	}
	
	public int getLeagueId() throws SQLException {
		int id = Integer.valueOf(getSessionId());
		LeagueSession leagueSession =
				_leagueSessionDao.getLeagueSessionById(id);
		return leagueSession.getLeagueId();
	}

	@Override
	protected String getSessionIdName() {
		return SESSION_ID_COOKIE_NAME;
	}
}
